# -*- coding:utf-8 -*-

from flask import request, render_template, jsonify
from flask_login import login_required
from app.tools.permission import permission
from app.tools.log import log
from app.tools.message import message
from app import db
from app.models.application import Purchase_Application as PA, Business_Application as BA, Advice
from app.models.account import Staff
import datetime
from . import assign


@assign.before_request
@login_required
@permission(['director', 'admin', 'super'])
def check_permission():	#检查权限
	return

@assign.route('/list/')
def assign_list():	#返回分配申请的界面，相关的申请数据由ajax异步获取
	services = Staff.query.filter_by(role='service').all()	#找出所有客服，用于分单时选择
	return render_template('tracking/assign/assign.html', services=services)
	 

@assign.route('/get_list/')
def get_list():	#获取待分配的申请
	limit = int(request.values.get('limit', '10'))
	offset = int(request.values.get('offset', '0'))
	app_type = request.values.get('app_type')	#申请类型
	if app_type is None:
		return jsonify({'state': -1, 'msg': u'参数不足'})
	if app_type == "buy":	#购车申请
		result = PA.query.filter_by(tracker_id=None).order_by(db.desc(PA.submission_date)).paginate(offset/limit+1, limit, False)
	elif app_type == "advice":	#投诉建议
		result = Advice.query.filter_by(tracker_id=None).order_by(db.desc(Advice.submission_date)).paginate(offset/limit+1, limit,False)
	else:	#业务申请
		result = BA.query.filter_by(tracker_id=None, application_type=app_type).order_by(db.desc(BA.submission_date)).paginate(offset/limit+1, limit, False)
	data = []
	count = result.total
	if app_type != 'advice':
		for item in result.items:
			data.append({
				'oid': item.id,
				'number': item.number,
				'title': item.car_title if app_type == 'buy' else item.product,
				'name': item.name,
				'phone': item.phone,
				'time': item.submission_date.strftime("%Y-%m-%d %H:%M:%S"),
				'area': item.area,
			})
	else:
		for item in result.items:
			data.append({
				'oid': item.id,
				'number': item.number,
				'type': u'建议' if item.type else u'投诉',
				'content': item.content,
				'name': item.name,
				'phone': item.phone,
				'time': item.submission_date.strftime("%Y-%m-%d %H:%M:%S"),
				'area': item.area,
			})
	json = {'total': count, 'rows': data}
	return jsonify(json)

@assign.route('/assign_app/', methods=['GET', 'POST'])
def assign():	#分配申请
	ids = request.values.get('order_ids')	#申请的id号，id号之间用；隔开
	service_id = request.values.get('customer_service')
	app_type = request.values.get('app_type')
	if ids is None or service_id is None or app_type is None:
		return jsonify({'state': -1, 'msg': u'参数不足'})
	if app_type not in ['advice', 'buy', 'rent', 'service', 'finance']:
		return jsonify({'state': 1, 'msg': u'参数错误'})
	service = Staff.query.filter_by(id=service_id, role='service').first()	#找出被分配到的客服
	if not service:
		return jsonify({'state': 2, 'msg': u'对象不存在'})
	if app_type == 'buy':
		dataset = PA
	elif app_type == 'advice':
		dataset = Advice
	else:
		dataset = BA
	ids = ids.split(';')[:-1]#取出单号
	for bid in ids:	#为申请指定跟进人
		result = dataset.query.filter_by(id=int(bid)).first()
		if result:
			result.tracker_id = service_id
			result.state = 1
			result.notice = service_id + ';'
			result.save()
			message(u"您有新的申请<a target='_blank' href='/tracking/track\
				/details/?app_number=%s&app_type=%s'>%s</a>待处理" % (result.number, app_type, result.number)
				, u'分单', server_id=service_id)
			log(u"将申请%s分配给客服%s" % (result.number, service.name))
	return jsonify({'state': 0})
